//
//  ChatViewController.m
//  BGM
//
//  Created by 我要变好看 on 2018/12/12.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "ChatViewController.h"
#import "Common.h"
#import "ChatTableViewCell.h"

#import <NIMSDK/NIMSDK.h>
#import "BGMUser.h"
#import "ChatInputView.h"
#import "PushMessageInfoViewController.h"
#import "ChatCustom.h"
#import "ChatCustomCell.h"
#import "FriendViewController.h"
#import "QBImagePickerController.h"

#import "ChatMoreView.h"
#import "ChatImageCell.h"
#import "ChatEmjonView.h"
#import "SVProgressHUD.h"
@interface ChatViewController ()

<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,
NIMChatManagerDelegate,ChatInputViewDelegate,NIMTeamManagerDelegate,NIMMediaManagerDelegate,
ChatCustomCellDelegate,ChatTableViewCellDelegate,ChatMoreViewDelegate,
QBImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate
>

@property (nonatomic, strong)UITableView *chatTable;
@property (nonatomic, strong)NSMutableArray *chatArray;  //聊天记录
@property (nonatomic, strong)ChatInputView *inputView;
@property (nonatomic, strong)ChatMoreView *moreView;
@property (nonatomic, strong)ChatEmjonView *emjonView;

@property (nonatomic, strong)NSArray *groupNumbers;
@property (nonatomic, strong)NSDictionary *groupMessagePulishDic;


@property (nonatomic, strong)NSString *voicePath;

@property (nonatomic,strong) UIImagePickerController *imagePickerController;
@property (nonatomic,strong) QBImagePickerController *qb_picker;
@property (nonatomic,strong) NSMutableArray *seleImagePathArray;

@property (nonatomic,strong) UIImageView *voiceImage;
@property (nonatomic,strong)NSTimer *recordTimer;
@property (nonatomic,assign)NSInteger totalRecordSeconds;


@property (nonatomic,assign)BOOL isKeyBoard;
@property (nonatomic,assign)CGFloat KeyBoardH;


@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    self.isKeyBoard = NO;
    [self.titleBtn setTitle:self.otherName forState:UIControlStateNormal];
    self.titleBtn.frame = CGRectMake(self.backBtn.frame.size.width, self.backBtn.frame.origin.y, SCREENW-self.backBtn.frame.size.width*2, self.backBtn.frame.size.height);
    
//    self.view.backgroundColor = [UIColor whiteColor];
    self.chatArray = [[NSMutableArray alloc]init];
    
    self.seleImagePathArray = [[NSMutableArray alloc]init];
    
    // 键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
    
    [self addTableViewHistory];

  
    self.inputView = [[ChatInputView alloc]initWithFrame:CGRectMake(0, SCREENH-(SCREENH>736?90:55), SCREENW, (SCREENH>736?90:55))];
    self.inputView.chatDelegate = self;
    [self.view addSubview:self.inputView];

    
    
    self.moreView = [[ChatMoreView alloc]initWithFrame:CGRectMake(0, SCREENH, SCREENW, SCREENW/4+40)];
    self.moreView.moreDelegate = self;
    [self.view addSubview:self.moreView];
    self.moreView.hidden = YES;
    
    
    
    self.emjonView = [[ChatEmjonView alloc]initWithFrame:CGRectMake(0, SCREENH, SCREENW, 200)];
//    self.moreView.moreDelegate = self;
    [self.view addSubview:self.emjonView];
    self.emjonView.hidden = YES;
    
    
    
    [[[NIMSDK sharedSDK]chatManager]addDelegate:self];
    [[[NIMSDK sharedSDK]teamManager]addDelegate:self];
    [[NIMSDK sharedSDK].mediaManager addDelegate:self];
    
 
 
    NIMMessageSearchOption *option = [[NIMMessageSearchOption alloc] init];
    option.limit = 0;
    option.allMessageTypes = YES;
    
    [[[NIMSDK sharedSDK]conversationManager] searchMessages:self.historysession option:option result:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.chatArray addObjectsFromArray:messages];
            [self.chatTable reloadData];
            [self tableVIewContentSize];
            if (self.isforewoard) {
                [self sendCustomMsg];
            }
        });

    }];
    
    if(self.isGroup){
        NIMTeam *team = [[[NIMSDK sharedSDK]teamManager] teamById:self.groupId];
        [self.titleBtn setTitle:team.teamName forState:UIControlStateNormal];
        self.navRightBtn.hidden = NO;
        [self.navRightBtn setTitle:@"详情" forState:UIControlStateNormal];
        [self.navRightBtn setTitleColor:bgmgrayColor forState:UIControlStateNormal];
        NSString *groupInfo = team.serverCustomInfo;
        if(groupInfo.length>0){
            NSError *error;
            NSData *jsonData = [groupInfo dataUsingEncoding:NSUTF8StringEncoding];
            
            
            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                       options:NSJSONReadingMutableContainers
                                                                         error:&error];
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]) {
                self.groupMessagePulishDic = jsonObject;
            }else{
                NSLog(@"json 解析错误");
            }
        }else{
            [SVProgressHUD showInfoWithStatus:@"获取群信息为空, team.serverCustomInfo"];
        }
      
        
        [[[NIMSDK sharedSDK]teamManager]fetchTeamMembers:self.groupId completion:^(NSError * _Nullable error, NSArray<NIMTeamMember *> * _Nullable members) {
            self.groupNumbers = members;
        }];
        
        
    }
    
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    self.voiceImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 130, 130)];
    for (int i = 0;i<6;i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"voiceImage%d",i+1]];
        [imageArray addObject:image];
    }
    self.voiceImage.animationImages = imageArray;
    self.voiceImage.animationDuration = 1;
    self.voiceImage.animationRepeatCount = 0;
    [self.view addSubview:self.voiceImage];
    self.voiceImage.center = CGPointMake(SCREENW/2, SCREENH/2);
    
}

- (void)tableVIewContentSize{
    if(self.chatArray.count>1){
        NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.chatArray.count-1 inSection:0];
        [self.chatTable scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark 发送自定义消息
- (void)sendCustomMsg{
   
    ChatCustom *customMsg = [[ChatCustom alloc]init];
    customMsg.helpUsersId = self.helpUsersId;
    customMsg.connectionUserId = self.connectionUserId;
    customMsg.messageId = self.messageId;
    
    if([self.messageInfo objectForKey:@"pType"]){
        customMsg.pushTitle = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"ptitle"]];
        customMsg.pushTxt = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"pcontent"]];
        customMsg.pushType = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"pType"]];
    }else{
        customMsg.pushTitle = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"publishTitle"]];
        customMsg.pushTxt = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"publishContent"]];
        customMsg.pushType = [NSString stringWithFormat:@"%@",[self.messageInfo objectForKey:@"typeId"]];
    }
   
    NIMCustomObject *ob =[[NIMCustomObject alloc]init];
    ob.attachment = customMsg;
    NIMMessage *message = [[NIMMessage alloc]init];
    message.messageObject = ob;
    message.text = @"【 分享帮忙信息 】";
    
    NIMSession *session = [NIMSession session:self.OtherId type:NIMSessionTypeP2P];
    
    //发送消息
    BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
    NSLog(@"发送消息结果 = %d",b);
    
    if (b) {  //fowardPusheMsgInfo
        if (self.isforewoardforHome) {
             [[NSNotificationCenter defaultCenter]postNotificationName:@"fowardPusheMsgInfoHome" object:self.messageInfo];
        }else{
           [[NSNotificationCenter defaultCenter]postNotificationName:@"fowardPusheMsgInfo" object:self.messageInfo];
        }
        
       
    }
    
    [self.chatArray addObject:message];
    [self.chatTable reloadData];
}
- (void)addTableViewHistory{
    self.chatTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height-70)];
    self.chatTable.dataSource = self;
    self.chatTable.delegate = self;
    self.chatTable.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];

    self.chatTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.chatTable];
    [self.view insertSubview:self.chatTable belowSubview:self.navview];
    [self.chatTable reloadData];
    
    
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.numberOfTapsRequired = 1;
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.chatTable addGestureRecognizer:gestureRecognizer];
    
 
   
//    [self.chatTable setContentOffset:CGPointMake(0, self.chatTable.contentSize.height-100) animated:NO];
//
//    [self.chatTable setContentOffset:CGPointMake(0, self.chatTable.contentSize.height) animated:YES];
//
//    CGFloat yOffset = 0; //设置要滚动的位置 0最顶部 CGFLOAT_MAX最底部
//    if (self.chatTable.contentSize.height > self.chatTable.bounds.size.height) {
//        yOffset = self.chatTable.contentSize.height - self.self.chatTable.bounds.size.height;
//        yOffset = self.chatTable.contentSize.height;
//    }
//    [self.chatTable setContentOffset:CGPointMake(0, yOffset) animated:YES];
    
}
- (void) hideKeyboard {
//    [textField resignFirstResponder];
   [self.inputView.chatText resignFirstResponder];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NIMMessage *message = [self.chatArray objectAtIndex:indexPath.row];
    if (message.messageType == NIMMessageTypeCustom) {
        return 200;
    }else if(message.messageType == NIMMessageTypeImage){
        return 240;
//        __block float h = 0.0;
//        [ChatImageCell chatImageHight:message finished:^(CGFloat width, CGFloat height) {
//            h = height;
//            NSLog(@"---------height1 = %.2f",h);
//        }];
//        NSLog(@"---------height2 = %.2f",h);
//        return h+40;
    }
    else{
        return  [ChatTableViewCell chatContentH:message];
    }
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    NIMMessage *message = [self.chatArray objectAtIndex:indexPath.row];
  
    if (message.messageType == NIMMessageTypeCustom) {
        
        static NSString *identifter = @"ChatCustomCell";
        ChatCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identifter];
        if (cell == nil) {
            cell = [[ChatCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifter];
            cell.customDelegate = self;
        }
        [cell setCustomMsg:message];
        return cell;

    }
    else if (message.messageType == NIMMessageTypeImage){
        NIMMessage *message = [self.chatArray objectAtIndex:indexPath.row];
        static NSString *identifter = @"ChatImageCell";
        ChatImageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifter];
        if (cell == nil) {
            cell = [[ChatImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifter];
        }
        [cell chatImage:message];
        return cell;
    }
    else{
        static NSString *identifter = @"ChatTableViewCell";
        ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifter];
        if (cell == nil) {
            cell = [[ChatTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifter];
            cell.otherImage = self.otherImage;
            cell.chatCellDelegate = self;
        }
         [cell chatContent:message];
         return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
}


#pragma mark 发送文本消息
-(void)sendChatText:(NSString *)text{
    
    NIMMessage *message = [[NIMMessage alloc] init];
    message.text = text;
    //构造会话
    if(self.isGroup){
        
        NIMSession *session = [NIMSession session:self.groupId type:NIMSessionTypeTeam];
        //发送消息
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];
        
    }else{
        NIMSession *session = [NIMSession session:self.OtherId type:NIMSessionTypeP2P];
        //发送消息
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];

    }
   
}
#pragma mark 发送图片消息
- (void)sendImageMsg:(UIImage *)image{

    //构造会话
    if(self.isGroup){
        NIMSession *session = [NIMSession session:self.groupId type:NIMSessionTypeTeam];
        NIMImageObject * imageObject = [[NIMImageObject alloc]initWithImage:image];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
        imageObject.displayName = [NSString stringWithFormat:@"图片发送于%@",dateString];
        NIMMessage *message     = [[NIMMessage alloc] init];
        message.messageObject   = imageObject;
        message.text = @"发来了一张图片";
        NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
        setting.scene = NIMNOSSceneTypeMessage;
        message.setting = setting;
        
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];
        
        
    }
    else{
        NIMSession *session = [NIMSession session:self.OtherId type:NIMSessionTypeP2P];
        NIMImageObject * imageObject = [[NIMImageObject alloc]initWithImage:image];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
        imageObject.displayName = [NSString stringWithFormat:@"图片发送于%@",dateString];
        NIMMessage *message     = [[NIMMessage alloc] init];
        message.messageObject   = imageObject;
        message.text = @"发来了一张图片";
        NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
        setting.scene = NIMNOSSceneTypeMessage;
        message.setting = setting;
        
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];
        
    }
    
    
    
}
#pragma mark 发送语音消息
- (void)sendVoiceMsg{
    //构造会话
    if(self.isGroup){
        NIMSession *session = [NIMSession session:self.groupId type:NIMSessionTypeTeam];
        //发送消息
        NIMAudioObject *audioObject = [[NIMAudioObject alloc] initWithSourcePath:self.voicePath scene:NIMNOSSceneTypeMessage];
        audioObject.duration = _totalRecordSeconds;
        NIMMessage *message = [[NIMMessage alloc] init];
        message.messageObject = audioObject;
        message.text = @"发来了一段语音";
        NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
        setting.scene = NIMNOSSceneTypeMessage;
        message.setting = setting;
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];
        
        
    }else{
        NIMSession *session = [NIMSession session:self.OtherId type:NIMSessionTypeP2P];
        //发送消息
        NIMAudioObject *audioObject = [[NIMAudioObject alloc] initWithSourcePath:self.voicePath scene:NIMNOSSceneTypeMessage];
        audioObject.duration = _totalRecordSeconds;
        NIMMessage *message = [[NIMMessage alloc] init];
        message.messageObject = audioObject;
        message.text = @"发来了一段语音";
        NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
        setting.scene = NIMNOSSceneTypeMessage;
        message.setting = setting;
        BOOL b = [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
        NSLog(@"发送消息结果 = %d",b);
        [self.chatArray addObject:message];
        [self.chatTable reloadData];
        [self tableVIewContentSize];
        
    }
    
    
    
}



#pragma mark 开始录音
- (void)startVioce{
    [self.voiceImage startAnimating];
    _totalRecordSeconds = 0;
    NIMAudioType type = NIMAudioTypeAAC;//[self recordAudioType];
    //    NSTimeInterval duration = [NIMKit sharedKit].config.recordMaxDuration;
    [[NIMSDK sharedSDK].mediaManager record:type
                                   duration:60];
     [self startRecordTimer];
}
- (void)endVioce{
    [self.voiceImage stopAnimating];
  
    [[NIMSDK sharedSDK].mediaManager stopRecord];
}
#pragma mark - Private Methods
- (void)startRecordTimer{
    if (!self.recordTimer) {
        self.recordTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(recordTimerAction) userInfo:nil repeats:YES];
        [self.recordTimer setFireDate:[NSDate distantPast]];
    }
}
- (void)recordTimerAction{
     _totalRecordSeconds += 1;
}
- (void)stopRecordTimer{
    if (self.recordTimer) {
        [self.recordTimer invalidate];
        self.recordTimer = nil;
        _totalRecordSeconds = 0;
     }
}


#pragma mark 结束录音回调
- (void)recordAudio:(nullable NSString *)filePath didCompletedWithError:(nullable NSError *)error{
    NSLog(@"录音结束");
    if (error == nil) {
        self.voicePath = filePath;
        [self sendVoiceMsg];
    }
}


#pragma mark 收到消息
- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages{
    for (NIMMessage * message in messages) {
        NIMSession *session = message.session;
        if (session.sessionType  == NIMSessionTypeTeam) {
            if (self.isGroup) {
                if ([session.sessionId isEqualToString:self.groupId]) {
                    [self.chatArray addObject:message];
                    [self.chatTable reloadData];
                    [self tableVIewContentSize];
                }
            }
            
        }else{
            if (!self.isGroup) {
                if ([session.sessionId isEqualToString:self.OtherId]) {
                    [self.chatArray addObject:message];
                    [self.chatTable reloadData];
                    [self tableVIewContentSize];
                }
            }
        }
    }
    
    
 
   
}

- (void)willSendMessage:(NIMMessage *)message{
    NSLog(@"将要发送消息");
}



#pragma mark 播放
- (void)clickMsg:(NIMMessage *)message{
    if (message.messageType == NIMMessageTypeAudio){
        NIMAudioObject *object = message.messageObject;
        NSString *url = object.path;
        [[[NIMSDK sharedSDK]mediaManager]play:url];
    }
}
-(void)playAudio:(NSString *)filePath didBeganWithError:(NSError *)error{
    NSLog(@"开始播放 %@",error);
    
}








- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(nullable NSError *)error{
    
//    if (error == nil) {  //消息发送成功
//        [self.chatArray addObject:message];
//        [self.chatTable reloadData];
//    }else{
//        
//    }
}

//重发
- (BOOL)resendMessage:(NIMMessage *)message
                error:(NSError **)error{
    return YES;
}
#pragma mark 更多
-(void)clickMoreBtn:(int)i{
    switch (i) {
        case 1:  //图片
            {
                [self openPhotoImage];
            }
            break;
        case 3:  //语音
        {
         }
            break;
        default:
            break;
    }
    
}

#pragma mark -键盘监听方法
- (void)keyboardWillShown:(NSNotification *)notification
{
    // 获取键盘的高度
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.KeyBoardH = frame.size.height;
    self.inputView.label.hidden = YES;
    self.isKeyBoard = YES;

    [UIView animateWithDuration:0.01 animations:^{
         self.inputView.frame = CGRectMake(0, SCREENH-frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
        CGFloat h = SCREENH-self.navview.frame.size.height-frame.size.height-self.inputView.frame.size.height;
         self.chatTable.frame = CGRectMake(0, self.navview.frame.size.height,SCREENW, h);
        
        [self tableVIewContentSize];
    }];
    
 
    
}
- (void)keyboardWillBeHiden:(NSNotification *)notification
{
//    if (self.inputView.chatText.text.length==0) {
//        self.inputView.label.hidden = NO;
//    }else{
//        self.inputView.label.hidden = YES;
//    }
    self.isKeyBoard = NO;

    if (self.moreView.hidden) {
        [UIView animateWithDuration:0.1 animations:^{
            self.inputView.frame = CGRectMake(0, SCREENH-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
            
            CGFloat h = SCREENH-self.navview.frame.size.height-self.inputView.frame.size.height;
            self.chatTable.frame = CGRectMake(0, self.navview.frame.size.height, SCREENW, h);
            [self tableVIewContentSize];
        }];
    }else{
//
        self.inputView.frame = CGRectMake(0, SCREENH-self.KeyBoardH-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
        CGFloat h = SCREENH-self.navview.frame.size.height-self.KeyBoardH-self.inputView.frame.size.height;
        self.chatTable.frame = CGRectMake(0, self.navview.frame.size.height,SCREENW, h);
        [self tableVIewContentSize];
        
    }
    
    
    
}

-(void)showNomalView{
    [self.inputView.chatText resignFirstResponder];
    self.moreView.hidden = NO;
    self.emjonView.hidden = YES;

    [UIView animateWithDuration:0.3 animations:^{
        self.inputView.frame =  CGRectMake(0,  SCREENH-self.moreView.frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
        self.moreView.frame = CGRectMake(0,  SCREENH-self.moreView.frame.size.height, SCREENW, self.moreView.frame.size.height);
 
        
        CGFloat h = SCREENH-self.navview.frame.size.height-self.inputView.frame.size.height-self.moreView.frame.size.height;
        self.chatTable.frame = CGRectMake(0, self.navview.frame.size.height,SCREENW, h);
        [self tableVIewContentSize];
        
    }];

    
  
}
-(void)hideNomalView{
    self.moreView.hidden = YES;
    if (self.isKeyBoard) {
        [UIView animateWithDuration:0.3 animations:^{
            self.moreView.frame = CGRectMake(0,  SCREENH-self.moreView.frame.size.height, SCREENW, self.moreView.frame.size.height);
            self.inputView.frame =  CGRectMake(0,  SCREENH-self.moreView.frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
            [self.inputView.chatText resignFirstResponder];
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            self.moreView.frame = CGRectMake(0,  SCREENH, SCREENW, self.moreView.frame.size.height);
            self.inputView.frame =  CGRectMake(0,  SCREENH-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
            [self.inputView.chatText resignFirstResponder];
        }];
        
    }
 
    
}


-(void)showEmjionView{
    
    [self.inputView.chatText resignFirstResponder];
    self.moreView.hidden = YES;
    self.emjonView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.inputView.frame =  CGRectMake(0,  SCREENH-self.emjonView.frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
        self.emjonView.frame = CGRectMake(0,  SCREENH-self.emjonView.frame.size.height, SCREENW, self.emjonView.frame.size.height);
        
        CGFloat h = SCREENH-self.navview.frame.size.height-self.inputView.frame.size.height-self.emjonView.frame.size.height;
        self.chatTable.frame = CGRectMake(0, self.navview.frame.size.height,SCREENW, h);
        [self tableVIewContentSize];
        
    }];

    
}
-(void)hideEmjionView{
    self.emjonView.hidden = YES;
    if (self.isKeyBoard) {
        [UIView animateWithDuration:0.3 animations:^{
            self.moreView.frame = CGRectMake(0,  SCREENH-self.moreView.frame.size.height, SCREENW, self.moreView.frame.size.height);
            self.inputView.frame =  CGRectMake(0,  SCREENH-self.moreView.frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
            [self.inputView.chatText resignFirstResponder];
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            self.moreView.frame = CGRectMake(0,  SCREENH, SCREENW, self.moreView.frame.size.height);
            self.inputView.frame =  CGRectMake(0,  SCREENH-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
            [self.inputView.chatText resignFirstResponder];
        }];
        
    }
}


#pragma mark 点击头像
- (void)findOtherInfo:(NSString *)otherId{
    NSString *userid = [BGMUser shareInstance].userId;
    if(![otherId isEqualToString:userid]){
        
        
        FriendViewController *vc = [[FriendViewController alloc]init];
        vc.userId = [BGMUser shareInstance].userId;
        vc.userToken = [BGMUser shareInstance].userToken;
        vc.chUsersId = otherId;
        vc.ftype = ChatFind;
        if(self.isGroup){
            vc.isRootGroupFrom = YES;
            vc.groupId = self.groupId;
        }else{
            vc.isRootGroupFrom = NO;

        }
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}
#pragma mark 查看信息详情
-(void)gotoPushInfo:(NIMMessage *)message{
    NIMCustomObject *cusstomObject =message.messageObject;
    ChatCustom *pushMsg = cusstomObject.attachment;
    
    NSString *pushType = pushMsg.pushType;
    PushMessageInfoViewController *vc = [[PushMessageInfoViewController alloc]init];
    if([pushType intValue]<8){
        vc.isPublicMsg = NO;
    }else{
        vc.isPublicMsg = YES;
    }
    vc.messageId = pushMsg.messageId;
    vc.helpUsersId = pushMsg.helpUsersId;
    vc.connectionUserId = pushMsg.connectionUserId;
    [self.navigationController pushViewController:vc animated:YES];
 
    
}



#pragma mark 相册
- (QBImagePickerController*)qb_picker{
    if (!_qb_picker) {
        _qb_picker = [QBImagePickerController new];
        _qb_picker.delegate = self;
        _qb_picker.showsNumberOfSelectedAssets = YES;
        _qb_picker.allowsMultipleSelection = YES;
    }
    [_qb_picker.selectedAssets removeAllObjects];
    return _qb_picker;
}
-(void)openPhotoImage{
//    self.qb_picker.maximumNumberOfSelection = 9-self.imageArray.count;
    [self presentViewController:self.qb_picker animated:YES completion:nil];
}
- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//- (BOOL)qb_imagePickerController:(QBImagePickerController *)imagePickerController shouldSelectAsset:(PHAsset *)asset{
//
//}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(PHAsset *)asset{
    
}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didDeselectAsset:(PHAsset *)asset{
    
}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    
    if (assets.count == 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return ;
    }else{
        [self.seleImagePathArray removeAllObjects];
        [self getLibraryPhotoImage:assets];
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getLibraryPhotoImage:(NSArray *)assets{
    dispatch_async(dispatch_get_main_queue(), ^{
        for (PHAsset *asset in assets) {
            
            PHImageManager * imageManager = [PHImageManager defaultManager];
            [imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                UIImage * image = [UIImage imageWithData:imageData];
                [self sendImageMsg:image];
            }];
            
        }
    });
}



- (void)clickRight{
    if(self.isGroup){
        PushMessageInfoViewController *vc = [[PushMessageInfoViewController alloc]init];
        vc.messageId = [NSString stringWithFormat:@"%@",[self.groupMessagePulishDic objectForKey:@"publishId"]];
        
        NSString *helpUsersId;
        if ([[self.groupMessagePulishDic objectForKey:@"helpUsersId"] isKindOfClass:[NSString class]]) {
            helpUsersId = [NSString stringWithFormat:@"%@",[self.groupMessagePulishDic objectForKey:@"helpUsersId"]];
        }else{
            helpUsersId = @"";
        }
        NSString *connectionUserId;
        if ([[self.groupMessagePulishDic objectForKey:@"connectionUserId"] isKindOfClass:[NSString class]]) {
            connectionUserId = [NSString stringWithFormat:@"%@",[self.groupMessagePulishDic objectForKey:@"connectionUserId"]];
        }else{
            connectionUserId = @"";
        }
        
        vc.helpUsersId = connectionUserId;
        vc.connectionUserId =@"";
        vc.isAccept = YES;
        vc.isTeam = YES;
        vc.teamArray = self.groupNumbers;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
 }


@end
